package com.rongmai.web.bo;

import com.rongmai.db.exception.BzException;
import com.rongmai.db.mapper.UserImgMapper;
import com.rongmai.db.model.UserImg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class FileBo {

    private static final String fileRootPath = "/usr/local/file/";

    @Resource
    private UserImgMapper userImgMapper;

    public UserImg saveFile(MultipartFile multipartFile) {
        String originalName = multipartFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String filePath = fileRootPath + uuid;
        if (!StringUtils.isEmpty(originalName)) {
            filePath += originalName.substring(originalName.lastIndexOf("."));
        }
        try {
            File file = new File(filePath);
            multipartFile.transferTo(file);
            return create(filePath, originalName);
        } catch (Exception e) {
            log.error("保存文件异常", e);
            throw new BzException("保存文件异常");
        }
    }

    public UserImg create(String path, String originalName) {
        UserImg userImg = new UserImg();
        userImg.setCreateTime(new Date());
        userImg.setImgName(originalName);
//        userImg.setMobile(user.getMobile());
//        userImg.setUserId(user.getId());
        userImg.setPath(path);
        userImgMapper.insert(userImg);
        return userImg;
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String originalName = "";
        System.out.println(uuid + originalName.substring(originalName.lastIndexOf(".")));
    }
}
